package com.lwhtarena.netty.netty4.server;

import com.lwhtarena.netty.netty4.util.FileInfo;
import com.lwhtarena.netty.netty4.util.FileInfoBuilder;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class WaitFileDecoder extends ByteToMessageDecoder {

    private static final Logger log = LoggerFactory.getLogger(WaitFileDecoder.class);
    private static volatile FileInfo fileInfo;
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

        Object decoded = decode(ctx, in);
        if (decoded != null) {
            out.add(decoded);
        }

    }

    protected Object decode(
            @SuppressWarnings("UnusedParameters") ChannelHandlerContext ctx, ByteBuf in) throws Exception {

        if (fileInfo == null) {
            String s = in.toString(CharsetUtil.US_ASCII);
            FileInfo info = FileInfoBuilder.convertFile(s);
            if(info != null){
                log.debug("接受的信息：{}",s);
                this.fileInfo = info;
                return fileInfo;
            }
        }
        return in.readRetainedSlice(in.readableBytes());
    }

}
